<?php
/**
 * 题目链接 https://leetcode.cn/problems/roman-to-integer/description/
 */

class Solution {

    /**
     * @param String $s
     * @return Integer
     */
    public static function romanToInt(string $s): int 
    {
        $map = [
            'I' => 1,
            'V' => 5,
            'X' => 10,
            'L' => 50,
            'C' => 100,
            'D' => 500,
            'M' => 1000,
        ];
        $len = strlen($s);
        $result = 0;

        if ($len <= 1) {
            return $map[$s[0]];
        } else {
            $result = $map[$s[0]];
        }
        for ($i=1; $i < $len; $i++) { 
            $result += $map[$s[$i]];
            // 正常右边的字符对应的值比左边的还大，则表明需要减去左边对应值的两倍
            if ($map[$s[$i - 1]] < $map[$s[$i]]) {
                $result -= $map[$s[$i - 1]] * 2;
            }
        }
        return $result;
    }

}

$test = [
    ["III"],
    ["IV"],
    ["IX"],
    ["LVIII"],
    ["MCMXCIV"],
];
$result = [
    3, 4, 9, 58, 1994,
];

foreach ($test as $key => $value) {
    $result = Solution::romanToInt($value[0]);
    echo $result . PHP_EOL;
}